//
//  OauthViewController.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/17.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit


class OauthViewController: UIViewController {

    ///微博oauth请求页面
    @IBOutlet weak var oauthWebView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let oauthString = "https://api.weibo.com/oauth2/authorize?client_id=\(Oauth_client_id)&redirect_uri=\(Oauth_redirect_uri)"
        guard let oauthURL = URL(string: oauthString) else {
            ZHLog("请求地址不对")
            return
        }
        let oauthRequest = URLRequest(url: oauthURL)
        
        oauthWebView.loadRequest(oauthRequest)
        
        //设置代理
        oauthWebView.delegate = self
    }
    /// 关闭登录页面
    @IBAction func loseButtonClick(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    /// 快速填充帐号
    @IBAction func addAccount(_ sender: Any) {
//        let jsStr = "document.getElementById('userId').value = '58899986@qq.com';"
//        customWebView.stringByEvaluatingJavaScriptFromString(jsStr)
        let accountStr = "document.getElementById('userId').value = '18621901664';"
        oauthWebView.stringByEvaluatingJavaScript(from: accountStr)
        
        let passwordStr = "document.getElementById('passwd').value = '18621901664';"
        oauthWebView.stringByEvaluatingJavaScript(from: passwordStr)
    }
}

//MARK:- UIWebViewDelegate
extension OauthViewController: UIWebViewDelegate{
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let abStr = request.url?.absoluteString else {
            return false
        }
        
        if !abStr.hasPrefix("http://www.baidu.com/") { //不是授权界面
            return true
        }

        //是授权界面
        let preCode = "code="
        guard let query = request.url?.query else {
            return false
        }
        
        if !query.hasPrefix(preCode) {
            return true
        }
        
        //截取字符串
        let code = String(query.suffix(from: preCode.endIndex))

        let parameters = ["client_id": Oauth_client_id, "client_secret": Oauth_client_secret, "grant_type": "authorization_code", "code": code, "redirect_uri": Oauth_redirect_uri]

        NetworkTools.sharedInstance.post("oauth2/access_token", parameters: parameters, progress: { (pro) in

        }, success: { (task, obj) in
            
            let userAccount = UserAccount(dict: obj as! [String: Any])

            userAccount.loadUserAccountInfo(finished: { (obj, error) in
                
                if error != nil {
                    ZHLog(error)
                }
                
                
                userAccount.saveUserAccount()
                
                
                
                SVProgressHUD.dismiss()
                
                self.dismiss(animated: true, completion: nil)
                
                // 授权完成发送跳转界面的通知
                NotificationCenter.default.post(name: NSNotification.Name(ZHTQViewControllerChangeNotification), object: false)

            })

        }) { (task, error) in
            ZHLog(error)
        }


        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show(withStatus: "加载中...")
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
